package org.jtb.neodroid;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.jtb.neoapi.Neo;
import org.jtb.neoapi.NeoFetcher;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ListNeoActivity extends Activity {
	private static final int UPDATE_WHAT = 0;
	private static final int FETCH_ERROR_WHAT = 1;

	private static final int SORT_DIALOG = 0;
	private static final int UNITS_DIALOG = 1;

	private static final int REFRESH_MENU = 0;
	private static final int SORT_MENU = 1;
	private static final int UNITS_MENU = 2;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_WHAT:
				update();
				break;
			case FETCH_ERROR_WHAT:
				Toast.makeText(
						mListNeoActivity,
						"Could not fetch NEOs, ensure you have a network connection and select Menu>Refresh",
						Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	private AlertDialog mSortDialog = null;
	private AlertDialog mUnitsDialog = null;

	private ListNeoActivity mListNeoActivity;
	private ListView mListView;
	private List<Neo> mNeos;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);

		/*
		 * mBannerImageView = (ImageView)findViewById(R.id.banner);
		 * mBannerImageView.setOnClickListener(new View.OnClickListener() {
		 * public void onClick(View v) { startActivity(new
		 * Intent(Intent.ACTION_VIEW, Uri.parse(Neo.NEO_URL))); } });
		 */

		mListNeoActivity = this;
		mListView = (ListView) findViewById(R.id.list);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Neo neo = mNeos.get(position);
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(neo
						.getUrl())));
			}
		});

		refresh();
	}

	private void refresh() {
		Toast.makeText(this, "Fetching NEOs, please wait ...",
				Toast.LENGTH_LONG).show();
		new Thread(new Runnable() {
			public void run() {
				try {
					mNeos = NeoFetcher.fetch();
					if (mNeos.size() == 0) {
						Log.e(getClass().getSimpleName(),
								"error fetching neos, size was 0");
						mHandler.sendMessage(Message.obtain(mHandler,
								FETCH_ERROR_WHAT));
					}
					mHandler.sendMessage(Message.obtain(mHandler, UPDATE_WHAT));
				} catch (Throwable t) {
					Log.e(getClass().getSimpleName(), "error fetching neos", t);
					mHandler.sendMessage(Message.obtain(mHandler,
							FETCH_ERROR_WHAT));
				}
			}
		}).start();
	}

	public void update() {
		Prefs p = new Prefs(this);
		String sort = p.getSort();
		String key = sort + "-" + p.getDirection(sort);

		Comparator<Neo> c = Neo.comparatorMap.get(key);
		Collections.sort(mNeos, c);
		NeoAdapter na = new NeoAdapter(this, mNeos);
		mListView.setAdapter(na);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, REFRESH_MENU, 0, R.string.refresh_menu).setIcon(
				R.drawable.refresh);
		menu.add(0, SORT_MENU, 1, R.string.sort_menu).setIcon(R.drawable.sort);
		menu.add(0, UNITS_MENU, 2, R.string.units_menu).setIcon(
				R.drawable.units);
		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case REFRESH_MENU:
			refresh();
			return true;
		case SORT_MENU:
			showDialog(SORT_DIALOG);
			return true;
		case UNITS_MENU:
			showDialog(UNITS_DIALOG);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case SORT_DIALOG:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setItems(new String[] { "Date", "Size", "Distance" },
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Prefs p = new Prefs(getBaseContext());
							String sort = null;
							switch (which) {
							case 0:
								sort = "date";
								break;
							case 1:
								sort = "size";
								break;
							case 2:
								sort = "distance";
								break;
							}
							if (sort.equals(p.getSort())) {
								p.toggleDirection(sort);
							}
							p.setSort(sort);

							mListNeoActivity.update();
						}
					});
			mSortDialog = builder.create();
			return mSortDialog;
		case UNITS_DIALOG:
			builder = new AlertDialog.Builder(this);
			builder.setItems(new String[] { "Metric", "US" },
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Prefs p = new Prefs(getBaseContext());
							switch (which) {
							case 0:
								p.setUnits("metric");
								break;
							case 1:
								p.setUnits("us");
								break;
							}
							mListNeoActivity.update();
						}
					});
			mUnitsDialog = builder.create();
			return mUnitsDialog;
		}
		return null;
	}

}